<template>
  <view class="edit-profile-page">

    
    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 头像设置 -->
      <view class="form-item avatar-item">
        <text class="form-label">头像</text>
        <view class="avatar-wrapper">
          <!-- 微信头像选择按钮 -->
          <button 
            class="avatar-button" 
            open-type="chooseAvatar"
            @chooseavatar="handleChooseAvatar"
          >
            <image 
              :src="formData.avatar || '/static/images/default-avatar.png'" 
              class="avatar-image" 
              mode="aspectFill"
            ></image>
            <view class="avatar-edit">
              <u-icon name="camera" size="16" color="#fff"></u-icon>
            </view>
          </button>
        </view>
      </view>
      
      <!-- 昵称设置 -->
      <view class="form-item">
        <text class="form-label">昵称</text>
        <!-- 微信昵称输入框 -->
        <input 
          type="nickname"
          v-model="formData.nickname"
          placeholder="请输入昵称"
          class="nickname-input"
          maxlength="20"
        />
      </view>
      
      <!-- 性别设置 -->
      <view class="form-item">
        <text class="form-label">性别</text>
        <u-radio-group v-model="formData.gender" placement="row">
          <u-radio 
            :customStyle="{marginRight: '32rpx'}"
            label="男" 
            :name="1"
          ></u-radio>
          <u-radio 
            label="女" 
            :name="2"
          ></u-radio>
        </u-radio-group>
      </view>
      
      <!-- 生日设置 -->
      <view class="form-item" @click="showDatePicker = true">
        <text class="form-label">生日</text>
        <view class="form-value">
          <text class="value-text" :class="{ placeholder: !formData.birthday }">
            {{ formData.birthday || '请选择生日' }}
          </text>
          <u-icon name="arrow-right" size="16" color="#c8c9cc"></u-icon>
        </view>
      </view>
      

    </view>
    
    <!-- 保存按钮 -->
    <view class="save-section">
      <u-button 
        type="primary" 
        :loading="saving"
        @click="saveProfile"
        :custom-style="saveButtonStyle"
      >
        保存
      </u-button>
    </view>
    
    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showDatePicker"
      v-model="dateValue"
      mode="date"
      @close="showDatePicker = false"
      @confirm="confirmDate"
    ></u-datetime-picker>
  </view>
</template>

<script>
/**
 * 编辑个人资料页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { userApi, uploadApi } from '@/api'
import { uploadImage } from '@/api/upload'
import { normalizeImageUrl } from '@/utils/common'

export default {
  data() {
    return {
      formData: {
        avatar: '',
        nickname: '',
        gender: 1,
        birthday: '',
      },
      saving: false,
      showDatePicker: false,
      dateValue: Number(new Date()),
      saveButtonStyle: {
        background: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
        border: 'none',
        borderRadius: '50rpx'
      },
    }
  },
  
  computed: {
    userInfo() {
      return this.$store.getters['user/userInfo']
    }
  },
  
  onLoad() {
      this.initFormData();
    },
  
  methods: {
    // 初始化表单数据
    initFormData() {
      if (this.userInfo) {
        this.formData = {
          avatar: normalizeImageUrl(this.userInfo.avatar) || '',
          nickname: this.userInfo.nickname || '',
          gender: this.userInfo.gender || 1,
          birthday: this.userInfo.birthday || '',
        }
        
        if (this.formData.birthday) {
          this.dateValue = Number(new Date(this.formData.birthday))
        }
      }
    },
    

    
    // 更换头像
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0]
          await this.uploadAvatar(tempFilePath)
        }
      })
    },
    
    // 上传头像
    async uploadAvatar(filePath) {
      uni.showLoading({
        title: '上传中...'
      })
      
      try {
        // 使用专门的文件上传工具函数
        const uploadInfo = await uploadImage(filePath)
        const info = uploadInfo?.upload_info || uploadInfo
        this.formData.avatar_id = info.id
        this.formData.avatar = normalizeImageUrl(info.url || info.path)
        uni.showToast({
          title: '头像上传成功',
          icon: 'success'
        })
        return uploadInfo
      } catch (error) {
        console.error('上传头像失败:', error)
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
        throw error
      } finally {
        uni.hideLoading()
      }
    },

    // 处理微信选择头像
    async handleChooseAvatar(e) {
      if (e.detail.avatarUrl) {
        // 将微信头像上传到服务器，获取图片ID
        uni.showLoading({
          title: '上传中...'
        })
        
        try {
          // 在微信小程序中，直接使用微信返回的临时文件路径进行上传
          const uploadInfo = await this.uploadAvatar(e.detail.avatarUrl)
          const info = uploadInfo?.upload_info || uploadInfo
          this.formData.avatar_id = info.id
          this.formData.avatar = normalizeImageUrl(info.url || info.path)
          uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          })
        } catch (error) {
          console.error('上传微信头像失败:', error)
          uni.showToast({
            title: error.message || '上传失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    },


    
    // 确认日期选择
    confirmDate(e) {
      const date = new Date(e.value)
      this.formData.birthday = date.toISOString().split('T')[0]
      this.showDatePicker = false
    },
    
    // 保存个人资料
    async saveProfile() {
      // 表单验证
      if (!this.formData.nickname.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
        return
      }
      
      this.saving = true
      
      try {
        // 准备提交数据，优先使用avatar_id，如果没有avatar_id但有avatar_url，则使用avatar_url
        const submitData = {
          nickname: this.formData.nickname,
          gender: this.formData.gender,
          birthday: this.formData.birthday
        }
        
        // 优先使用avatar_id，如果没有avatar_id但有avatar_url，则使用avatar_url
        if (this.formData.avatar_id) {
          submitData.avatar_id = this.formData.avatar_id
        } else if (this.formData.avatar) {
          submitData.avatar_url = this.formData.avatar
        }
        
        await userApi.updateProfile(submitData)
        const info = await userApi.getUserInfo()
        await this.$store.dispatch('user/updateUserInfo', info)
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('保存个人资料失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style scoped>
.edit-profile-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item.avatar-item {
  justify-content: space-between;
}

.form-item.textarea-item {
  align-items: flex-start;
  flex-direction: column;
}

.form-label {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  min-width: 120rpx;
}

.avatar-wrapper {
  position: relative;
}

.avatar-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid #fff;
}

/* 微信头像按钮样式 */
.avatar-button {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  line-height: 1;
}

.avatar-button::after {
  border: none;
}

/* 微信昵称输入框样式 */
.nickname-input {
  flex: 1;
  height: 40rpx;
  font-size: 30rpx;
  color: #333;
  border: none;
  outline: none;
  margin-left: 30rpx;
  background: transparent;
}

/* 微信授权按钮样式 */
.wechat-auth-btn {
  margin-left: 20rpx;
  padding: 8rpx 16rpx;
  background: #fff;
  border: 1rpx solid #07C160;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #07C160;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.wechat-auth-btn::after {
  border: none;
}

.wechat-auth-btn text {
  margin-left: 8rpx;
}

.form-value {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 30rpx;
}

.value-text {
  font-size: 30rpx;
  color: #333;
}

.value-text.placeholder {
  color: #c8c9cc;
}

.textarea-item .form-label {
  margin-bottom: 20rpx;
}

.save-section {
  padding: 40rpx 30rpx;
}
</style>
